<template>
  <div class="component-renderer" :data-component-id="component.id">
    <!-- 图表组件 -->
    <div 
      v-if="isChartComponent"
      ref="chartRef"
      class="chart-container"
      :style="{ width: '100%', height: '100%' }"
    ></div>

    <!-- 文本组件 -->
    <div 
      v-else-if="component.type === ComponentType.TEXT"
      class="text-component"
      :style="{
        fontSize: component.config.fontSize + 'px',
        color: component.config.fontColor,
        fontWeight: component.config.fontWeight,
        textAlign: component.config.textAlign,
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: component.config.textAlign === 'center' ? 'center' : 
                       component.config.textAlign === 'right' ? 'flex-end' : 'flex-start'
      }"
    >
      {{ component.config.text }}
    </div>

    <!-- 图片组件 -->
    <img 
      v-else-if="component.type === ComponentType.IMAGE"
      :src="component.config.src"
      class="image-component"
      :style="{
        width: '100%',
        height: '100%',
        objectFit: 'cover'
      }"
      @error="handleImageError"
    />

    <!-- 边框组件 -->
    <div 
      v-else-if="component.type === ComponentType.BORDER"
      class="border-component"
      :style="{
        width: '100%',
        height: '100%',
        border: getBorderStyle(component.config.borderType),
        borderRadius: component.style.borderRadius + 'px'
      }"
    ></div>

    <!-- 未知组件类型 -->
    <div v-else class="unknown-component">
      <el-icon><QuestionFilled /></el-icon>
      <span>未知组件</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ComponentType, type Component } from '@/types'

interface Props {
  component: Component
}

const props = defineProps<Props>()

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 判断是否为图表组件
const isChartComponent = computed(() => {
  return [
    ComponentType.BAR_CHART,
    ComponentType.LINE_CHART,
    ComponentType.PIE_CHART,
    ComponentType.RADAR_CHART
  ].includes(props.component.type)
})

// 初始化图表
const initChart = async () => {
  if (!isChartComponent.value || !chartRef.value) return
  
  await nextTick()
  
  // 销毁已存在的图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  
  try {
    chartInstance = echarts.init(chartRef.value, 'dark')
    
    // 设置图表配置
    const option = {
      ...props.component.config.chartOption,
      animation: true,
      backgroundColor: 'transparent'
    }
    
    chartInstance.setOption(option)
    
    // 监听窗口大小变化
    const resizeObserver = new ResizeObserver(() => {
      if (chartInstance) {
        chartInstance.resize()
      }
    })
    
    resizeObserver.observe(chartRef.value)
    
    // 保存观察器引用以便清理
    ;(chartInstance as any)._resizeObserver = resizeObserver
  } catch (error) {
    console.error('Chart initialization error:', error)
  }
}

// 更新图表
const updateChart = () => {
  if (!chartInstance || !props.component.config.chartOption) return
  
  try {
    const option = {
      ...props.component.config.chartOption,
      animation: true,
      backgroundColor: 'transparent'
    }
    
    chartInstance.setOption(option, true)
  } catch (error) {
    console.error('Chart update error:', error)
  }
}

// 获取边框样式
const getBorderStyle = (borderType: string = 'solid') => {
  const borderWidth = '2px'
  const borderColor = '#409eff'
  
  switch (borderType) {
    case 'dashed':
      return `${borderWidth} dashed ${borderColor}`
    case 'dotted':
      return `${borderWidth} dotted ${borderColor}`
    case 'double':
      return `${borderWidth} double ${borderColor}`
    default:
      return `${borderWidth} solid ${borderColor}`
  }
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = ''
}

// 监听组件配置变化
watch(
  () => props.component.config,
  () => {
    if (isChartComponent.value) {
      updateChart()
    }
  },
  { deep: true }
)

// 监听组件类型变化
watch(
  () => props.component.type,
  () => {
    if (isChartComponent.value) {
      nextTick(() => {
        initChart()
      })
    }
  }
)

onMounted(() => {
  if (isChartComponent.value) {
    initChart()
  }
})

onUnmounted(() => {
  if (chartInstance) {
    // 清理 ResizeObserver
    if ((chartInstance as any)._resizeObserver) {
      ;(chartInstance as any)._resizeObserver.disconnect()
    }
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
.component-renderer {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart-container {
  width: 100%;
  height: 100%;
}

.text-component {
  padding: 8px;
  word-wrap: break-word;
  overflow: hidden;
}

.image-component {
  border-radius: inherit;
}

.border-component {
  background: rgba(255, 255, 255, 0.05);
}

.unknown-component {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #999;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px dashed #666;
}

.unknown-component .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}
</style>